<template>
  <div>
    <el-button type="primary" @click="showDialog()">新增管理员</el-button>
    <el-table :data="list" class="ymd-table">
      <el-table-column
        prop="id"
        label="id"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        label="名字"
      >
      </el-table-column>
    </el-table>
    <el-dialog title="添加管理员" :visible.sync="dialogVisible">
      <el-form
        :model="form"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="用户名">
          <el-input v-model="form.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as apis from 'services/admin'
import { mapState } from 'vuex'

export default {
  name: 'AdminList',
  computed: {
    ...mapState({
      list: state => state.admin.list,
    }),
  },
  data() {
    return {
      dialogVisible: false,
      form: {
        name: '',
        password: '',
      },
    }
  },
  created() {
    this.$store.dispatch('getAdminList')
  },
  methods: {
    showDialog() {
      this.dialogVisible = true
    },
    hideDialog() {
      this.dialogVisible = false
    },
    confirm() {
      const payload = {
        ...this.form,
        rePassword: this.form.password,
      }

      apis.addAdmin(payload)
        .then(() => {
          this.$message({
            type: 'success',
            message: '保存成功!',
          })
          this.hideDialog()
          this.$store.dispatch('getAdminList')
        })
        .catch(() => {
          this.$message({
            type: 'error',
            message: '保存失败',
          })
        })
    },
  },
}
</script>

<style>

</style>
